/**
 * Project Name:fastPlat
 * File Name:DictionaryController.java
 * Package Name:com.fast.cms.web.controller.admin
 * Date:2014年12月17日下午2:59:27
 * Copyright (c) 2014, lsflu@126.com All Rights Reserved.
 *
*/

package com.fast.cms.web.controller.system;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fast.base.db.page.PageView;
import com.fast.base.db.page.QueryResult;
import com.fast.base.db.sql.AbstractSqlGenerator;
import com.fast.base.model.AnoSysLog;
import com.fast.base.util.ChineseSpelling;
import com.fast.base.util.LogUtils;
import com.fast.base.util.data.MathUtils;
import com.fast.base.util.web.ResponseData;
import com.fast.base.web.BaseController;
import com.fast.cms.model.system.Dictionary;
import com.fast.cms.service.article.MdDataService;
import com.fast.cms.service.system.DictionaryService;
import com.fast.common.userCache.UserRequestUtils;

/**
 * ClassName:DictionaryController <br/>
 * 用途: 数据字典业务控制 <br/>
 * 开发人员：lushuifa  http://lushuifa.iteye.com/
 * 邮箱:lsflu@126.com
 * @version  
 * @since    JDK 1.6
 * @see
 * Date:     2014年12月17日 下午2:59:27 <br/> 	 
 */
@Controller
@RequestMapping("/dictionary")
public class DictionaryController extends BaseController{
	
	@Resource(name="dictionaryService")
	private DictionaryService beanService;
	
	@Autowired
	private MdDataService mdDataService;
	
	/**
	 * 得到字典数据，主要用于下拉框选择用
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/getDicListForSelecter.do",method=RequestMethod.POST)
	public ResponseData getDicListForSelecter(String parentUUID) throws Exception {
		ResponseData responseData = new ResponseData();
		try {
			List<Map<String,Object>> dicList = this.beanService.getDictionaryListByParentUUID(parentUUID);
			responseData.setData(dicList);
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	/**
	 * 得到字典数据，主要用于下拉框选择用
	 * 此方法包含子链接数据
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/getDicListWithChildsForSelecter.do",method=RequestMethod.POST)
	public ResponseData getDicListWithChildsForSelecter(String parentUUID) throws Exception {
		ResponseData responseData = new ResponseData();
		try {
			List<Map<String,Object>> dicList = this.beanService.getDicListWithChildsForSelecter(parentUUID);
			responseData.setData(dicList);
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	
	/**
	 * 得到产品类型
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/getDicForProductType.do",method=RequestMethod.POST)
	public JSONArray getDicForProductType() throws Exception {
		String parentUUID = webUtil.getString("id");
		if(parentUUID.equals("")){
			parentUUID="201503091122570477966";
		}
		return this.beanService.getTreeGridData(parentUUID);
	}
	
	/**
	 * 通过父类id得到子类列表
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/getDicListByParentUUID.do")
	public JSONObject getDicListByParentUUID(){
		String parentUUID = webUtil.getString("parentid");
		List<Map<String,Object>> mapList = this.beanService.queryForMapList("uuid,parentUUID,dicname,diccode", AbstractSqlGenerator.getTableName(Dictionary.class), " where parentUUID='"+parentUUID+"'");
		JSONObject jo = new JSONObject();
		jo.put("dicList", mapList);
		return jo;
	}
	
	/**
	 * 标题：getDictionaryList4Tree <br/>
	 * 作用：得到数据字典     <br/>
	 * @author developer-lushuifa
	 * @throws Exception
	 * @since JDK 1.6
	 */
	@ResponseBody
	@RequestMapping(value="/getDictionaryList4Tree.do")
	public JSONArray getDictionaryList4Tree() throws Exception {
		String parentUUID = webUtil.getString("id");
		boolean isRoot = false;
		if(parentUUID.equals("")){
			parentUUID="0";
			if(!webUtil.getString("parentUUID").equals("")){
				parentUUID=webUtil.getString("parentUUID");
				isRoot = true;
			}
		}
		return this.beanService.getDicTreeData(parentUUID,isRoot);
	}

	/**
	 * 编辑[数据字典]信息
	 * @param Dictionary
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/editDictionary.do")
	@AnoSysLog(actionName="编辑[数据字典]信息")
	public ResponseData editDictionary() {
		ResponseData responseData = new ResponseData();
		Dictionary dictionary = null;
		try {
			int id = webUtil.getInt("id");
			if (id > 0) {
				dictionary = this.beanService.queryForBeanById(Dictionary.class, id);
				dictionary = (Dictionary) webUtil.bindDataToBean(dictionary);
			} else {
				dictionary = new Dictionary();
				dictionary = (Dictionary) webUtil.bindDataToBean(dictionary);
				dictionary.setUuid(MathUtils.getTheOnlyStr());
				UserRequestUtils.bindCreaterInfo(dictionary);
				dictionary.setSortid(this.beanService.getSortId(dictionary.getParentUUID()));
				dictionary.setDepth(beanService.genDicDepth(dictionary.getParentUUID()));
			}
			// 当存在UUID时的处理
			dictionary.setAliasName(ChineseSpelling.getSpell(dictionary.getDicname()));
			UserRequestUtils.bindEditorInfo(dictionary);
			if (this.beanService.saveOrUpdateDictionary(dictionary) != null) {
				responseData.setMsg("编辑编号为[" + dictionary.getUuid() + "]操作成功");
			}
			responseData.setCode("00");
		} catch (Exception e) {
			e.printStackTrace();
			responseData.setMsg("编辑编号为[" + dictionary.getUuid() + "]操作失败");
		}
		return responseData;
	}
	
	/**
	 * 更新字典数据
	 * @param Dictionary
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/updateDictionary.do")
	@AnoSysLog(actionName="编辑[数据字典]信息")
	public ResponseData updateDictionary() {
		ResponseData responseData = new ResponseData();
		Dictionary dictionary = null;
		try {
			int id = webUtil.getInt("id");
			if (id > 0) {
				dictionary = this.beanService.queryForBeanById(Dictionary.class, id);
				dictionary = (Dictionary) webUtil.bindDataToBean(dictionary);
			}
			// 当存在UUID时的处理
			UserRequestUtils.bindEditorInfo(dictionary);
			if (this.beanService.merge(dictionary) != null) {
				responseData.setMsg("编辑编号为[" + dictionary.getUuid() + "]操作成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	/**
	 * 批量编辑[数据字典]信息
	 * @param formData
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/editAllDictionary.do")
	@AnoSysLog(actionName="批量编辑[数据字典]信息")
	public ResponseData editAllDictionary(String formData) {
		List<Dictionary> psmList = JSONArray.parseArray(formData.replace("&quot;", "\'"), Dictionary.class);
		ResponseData responseData = new ResponseData();
		try {
			int actionCount = psmList.size();
			int success = 0,failure= 0,count = 0;
			for (Dictionary dictionary : psmList) {
				count++;
				//设计唯一UUID
				dictionary.setUuid(MathUtils.getTheOnlyStr());
				if(dictionary.getDicCode().equals("")){
					dictionary.setDicCode("DIC"+count);
				}
				//设置权限编码
				dictionary.setDepth(beanService.genDicDepth(dictionary.getParentUUID()));
				dictionary.setSortid(this.beanService.getSortId(dictionary.getParentUUID()));
				dictionary.setAliasName(ChineseSpelling.getSpell(dictionary.getDicname()));
				//设置操作人编辑人
				UserRequestUtils.bindCreaterInfo(dictionary);
				UserRequestUtils.bindEditorInfo(dictionary);
				try{
					beanService.persist(dictionary);
					success++;
				}catch(Exception e){
					failure++;
				}
				Thread.sleep(50);
			}
		    responseData.setMsg("批量操作结果为：共添加数据["+actionCount+"],成功保存["+success+"],失败保存["+failure+"]");
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	/**
	 * 删除[数据字典]信息
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delDictionary.do")
	@AnoSysLog(actionName="删除字典信息")
	public ResponseData delDictionary(int id) {
		String deleteChild = webUtil.getString("deleteChild");
		ResponseData responseData = new ResponseData();
		final Dictionary bean = beanService.queryForBeanById(Dictionary.class, id);
		try {
			if (bean.getParentUUID().equals("20180901153619147993375")||bean.getParentUUID().equals("20180901153619037752948")) {
				mdDataService.repeatCheckMianGanCi(bean.getDicname());
			}
			if(deleteChild.equals("true")){
				Thread dChild = new Thread(){
					@Override
					public void run() {
						List<Map<String,Object>> dataList = beanService.getDicTreeList(bean.getUuid(),"uuid,parentUUID,parentName,dicname");
					    this.batchDelete(dataList);
					}

					private void batchDelete(List<Map<String, Object>> dataList) {
						for (Map<String, Object> map : dataList) {
							beanService.deleteByUUID(Dictionary.class, map.get("uuid").toString());
							if(map.get("children")!=null){
								batchDelete((List<Map<String, Object>>) map.get("children"));
							}
						}
					}
				};
				dChild.start();
			}
			beanService.remove(bean);
			responseData.setCode("00");
			responseData.setMsg("删除["+bean.getDicname()+"]操作成功");
		} catch (Exception e) {
			e.printStackTrace();
			responseData.setCode("01");
			responseData.setMsg("删除["+bean.getDicname()+"]操作失败");
		}
		return responseData;
	}
	
	/**
	 * 删除多个[数据字典]信息
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delMoreDictionary.do")
	public ResponseData delMoreDictionary(String ids) {
		ResponseData responseData = new ResponseData();
		try {
			int actionCount = beanService.deleteByIds(Dictionary.class, ids);
			mdDataService.repeatCheckMianGanCi("");
			responseData.setCode("00");
			responseData.setMsg("删除[数据字典]编号为["+ids+"]操作成功,共成功["+actionCount+"]");
		} catch (Exception e) {
			e.printStackTrace();
			responseData.setCode("01");
			responseData.setMsg("删除[数据字典]["+ids+"]操作失败");
		}
		return responseData;
	}
	
	/**
	 * 得到数据字典详细信息
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getJsonDetail.do")
	public ResponseData getJsonDetail(int id) {
		ResponseData responseData = new ResponseData();
		Dictionary bean = beanService.queryForBeanById(Dictionary.class, id);
		try {
			responseData.setCode("00");
			responseData.setData(bean);
			responseData.setMsg("获取信息成功");
		} catch (Exception e) {
			e.printStackTrace();
			responseData.setCode("01");
			responseData.setMsg("获取信息失败");
		}
		return responseData;
	}
	
	/**
	 * 得到[数据字典]列表
	 * @param Dictionary
	 * @param session
	 * @param request
	 * @return
	 * @throws IOException 
	 */
	@ResponseBody
	@RequestMapping("/getDictionaryList.do")
	public Map<String,Object> getDictionaryList() throws IOException {
		int page = webUtil.getInt("page",1);//当前页
  		int pagesize = webUtil.getInt("rows");//每页面显示多少条
  		String parentUUID = webUtil.getString("parentUUID");
  		String dicName = webUtil.getString("dicName");
		StringBuffer sb = new StringBuffer(" where 1=1 ");
		
		if(StringUtils.isNotBlank(dicName)){
			sb.append(" and dicname like '%"+dicName+"%' ");
		}
		
		if(StringUtils.isNotBlank(parentUUID)){
			sb.append(" and parentUUID='"+parentUUID+"' ");
		}else{
			sb.append(" and parentUUID='0' ");
		}
		String ordersql = " order by sortid asc,edit_time desc ";
		QueryResult<Dictionary>  queryResult = this.beanService.queryForBeanListByPage(Dictionary.class, sb.toString(), ordersql,(page-1)*pagesize,pagesize);
		PageView<Dictionary> pageView = new PageView<Dictionary>();
	    pageView.setCurrentPage(page);
		pageView.setQueryResult(queryResult);
		return pageView.toEasyUIMap();
	}
	
	/**
	 * 得到[数据字典]列表
	 * @param Dictionary
	 * @param session
	 * @param request
	 * @return
	 * @throws IOException 
	 */
	@ResponseBody
	@RequestMapping("/js/getDictionaryList.do")
	public PageView<Dictionary> getAjaxDictionaryList() throws IOException {
		LogUtils.info("getAjaxAdminList is comming!");
		PageView<Dictionary> pageView = new PageView<Dictionary>();
		int currentPage = webUtil.getInt("page",1);//当前页
  		int pageSize = webUtil.getInt("pageSize",10);//每页面显示多少条
  		String parentUUID = webUtil.getString("parentUUID");
  		try {
  			StringBuffer sb = new StringBuffer(" where 1=1 ");
  			if(!"".equals(parentUUID)){
  				sb.append(" and parentUUID='"+parentUUID+"' ");
  			}else{
  				sb.append(" and parentUUID='0' ");
  			}
  			String ordersql = " order by sortid asc,edit_Time desc ";
  			QueryResult<Dictionary>  queryResult = this.beanService.queryForBeanListByPage(Dictionary.class, sb.toString(), ordersql,(currentPage-1)*pageSize,pageSize);
  		    pageView.setCurrentPage(currentPage);
  			pageView.setQueryResult(queryResult);
		} catch (Exception e) {
			e.printStackTrace();
			LogUtils.error("getAjaxDictionaryList err:",e);
		}
		return pageView;
	}
	
	/**
	 * 得到[数据字典]列表
	 * @param Dictionary
	 * @param session
	 * @param request
	 * @return
	 * @throws IOException 
	 */
	@ResponseBody
	@RequestMapping("/js/getAjaxDictionaryListWithChilds.do")
	public PageView<Dictionary> getAjaxDictionaryListWithChilds(String parentUUID) throws IOException {
		LogUtils.info("getAjaxAdminList is comming!");
		PageView<Dictionary> pageView = new PageView<Dictionary>();
		int currentPage = webUtil.getInt("page",1);//当前页
  		int pageSize = webUtil.getInt("pageSize",10);//每页面显示多少条
  		try {
  			QueryResult<Dictionary>  queryResult = new QueryResult<Dictionary>();
  			List<Dictionary> allDicList = this.beanService.getDicListWithAllChilds(parentUUID);
  			//切分
  			int startIndex = (currentPage-1)*pageSize;
  			int endIndex = (currentPage-1)*pageSize+pageSize;
  			if(endIndex>=allDicList.size()){
  				endIndex = allDicList.size();
  			}
  			List<Dictionary> resultList = allDicList.subList(startIndex,endIndex);
  			queryResult.setResultList(resultList);
  			queryResult.setTotalRecord(allDicList.size());
  		    pageView.setCurrentPage(currentPage);
  			pageView.setQueryResult(queryResult);
		} catch (Exception e) {
			e.printStackTrace();
			LogUtils.error("getAjaxDictionaryList err:",e);
		}
		return pageView;
	}
	
	/**
	 * 得到数据字典下拉列表
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getDictionaryList4comboBox.do")
	public List<Dictionary> getDictionaryList4comboBox(String parentUUID){
		List<Dictionary> dicList =  this.beanService.queryForBeanList(Dictionary.class, " where parentUUID='"+parentUUID+"'");
	    return dicList;
	}
		
	/**
	 * 查询详情
	 * @param id
	 * @return
	 */
	@RequestMapping("/getDictionaryDetail.do")
	public ModelAndView getDictionaryDetail(@RequestParam(required=true) int id) {
		ModelAndView mv = new ModelAndView();
		Dictionary bean = this.beanService.queryForBeanById(Dictionary.class, id);
		try {
			mv.addObject("dictionary",bean);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String actionType = webUtil.getString("actionType");
		switch (actionType) {
			case "update":
				mv.setViewName("/adminMain/system/type-add.jsp");
				break;
			default:
				mv.setViewName("/adminMain/system/type-detail.jsp");
				break;
		}
		return mv;
	}
	
}

